const ejs = require('ejs')
const fs = require('fs')
const path = require('path')
const program = require('commander')
const chalk = require('chalk')
const inquirer = require('inquirer')

program.version('1.0', '-v, --version').usage('<type>')

program
  .command('create')
  .argument(
    '<type>',
    'the algorithm type to create,  "o" for order & "s" for search'
  )
  .description('create an order algorithm')
  .action(async (type) => {
    let templateFile = ''
    let dir = ''
    if (type === 'o') {
      templateFile = './template/order_algori.ejs'
      dir = './src/order'
    } else {
      // FIXME: add search template and fix this part
      console.log(chalk.red(' Not support for moment, using order template '))
      templateFile = './template/order_algori.ejs'
      dir = './src/order'
    }
    const { filename } = await inquirer.prompt([
      {
        name: 'filename',
        type: '',
        message: `Enter the algorithm name you prefer: `,
      },
    ])

    const filepath = path.join(dir, filename + '.js')
    if (fs.existsSync(filepath)) {
      console.log(chalk.render(`the filename you enter has existed!`))
      return
    }

    const template = fs.readFileSync(templateFile, {
      encoding: 'UTF8',
      flag: 'r',
    })
    const data = {
      algorithmName: filename,
    }
    const renderString = ejs.render(template, data)

    const ws = fs.createWriteStream(filepath)
    ws.write(renderString, 'UTF8')
    ws.end()
  })

program.arguments('<type>').action((cmd) => {
  program.outputHelp()
  console.log(`  ` + chalk.red(`Unknown command ${chalk.yellow(cmd)}.`))
  console.log()
})

program.parse(process.argv)
